#coding: utf-8
import sys
sys.path.append('C:/workspace/mysite')
from mysite.settings import ssh_host,ssh_password,ssh_port,ssh_username
import paramiko

def ssh_command(cmd):
    result = ''
    errorInfo = ''
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ssh_host,ssh_port,ssh_username, ssh_password,timeout=5)
    stdin, stdout, stderr = ssh.exec_command(cmd)
    err = stderr.readlines()
    if err:
        errorInfo = err[0]
    else:
        result = stdout.readlines()
    ssh.close()
    return (result,errorInfo)

def upload_file(source_file, target_file):
    t = paramiko.Transport((ssh_host,ssh_port))
    t.connect(username = ssh_username, password = ssh_password)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.put(source_file,target_file)
    t.close()

def download_file(source_file, target_file):
    t = paramiko.Transport((ssh_host,ssh_port))
    t.connect(username = ssh_username, password = ssh_password)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.get(source_file,target_file)
    t.close()


def remote_lr_operate(filepath,search=None):
    final_result = []
    (result,error) = ssh_command('ls -lR ' + filepath)
    if error:
        return (result,error)
    idx = -1
    tmppath = ''
    final_result = []
    for i in result:
        idx += 1
        iArr = i.strip().split()
        if len(iArr) ==  2 and iArr[0]=='total' and iArr[1].isdigit():
            tmppath = result[idx - 1].strip()
            if tmppath.endswith(":"):
                tmppath = tmppath[0:len(tmppath) - 1]
            if not tmppath.endswith("/"):
                tmppath += '/'
        elif len(iArr) > 2 and not iArr[0].startswith('d'):
            filename = iArr[len(iArr) - 1]
            filename = tmppath + filename
            if not search:
                final_result.append(filename)
            elif filename.startswith(search):
                final_result.append(filename)
    return (final_result,'')

# def remote_lr_operate(filepath):
#     final_result = []
#     result = ssh_command('ls -lR ' + filepath)
#     idx = -1
#     tmppath = ''
#     filepathList = []
#     file_result = {}
#     for i in result:
#         idx += 1
#         iArr = i.strip().split()
#         if len(iArr) ==  2 and iArr[0]=='total' and iArr[1].isdigit():
#             tmppath = result[idx - 1].strip()
#             if tmppath.endswith(":"):
#                 tmppath = tmppath[0:len(tmppath) - 1]
#                 file_result[tmppath] = []
#                 filepathList.append(tmppath)
#         elif len(iArr) > 2 and not iArr[0].startswith('d'):
#             filename = iArr[len(iArr) - 1]
#             file_result[tmppath].append(filename)
#     for filepath in filepathList:
#         if file_result.has_key(filepath):
#             for filename in file_result[filepath]:
#                 final_result.append(filepath+'/'+filename)
#     return file_result

if __name__ =="__main__":
    print remote_lr_operate('/srv/salt','/srv/salt/test')

